package com.ilarele.shopping.server;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class SendImage implements Runnable {
	private Socket socket;

	public SendImage(Socket socket) {
		System.out.println("send image");
		this.socket = socket;
		new Thread(this).start();
	}

	@Override
	public void run() {
		// recv name
		ObjectInputStream ois = null;
		// read from file
		FileInputStream fin = null;
		// send img
		DataOutputStream dos = null;

		try {
			// read name
			ois = new ObjectInputStream(socket.getInputStream());
			String picName = (String) ois.readObject();

			// read from file & write in output stream
			fin = new FileInputStream(
					ConnectionConstants.PICTURES_FOLDER.getAbsolutePath()
							+ "/" + picName);
			dos = new DataOutputStream(socket.getOutputStream());
			int i;
			while ((i = fin.read()) > -1) {
				dos.write(i);
			}

			//
			System.out.println("image send " + picName);
			fin.close();
			ois.close();
			dos.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (fin != null)
					fin.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (dos != null)
					dos.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (ois != null)
					ois.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
